<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 添加角色按钮 -->
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-button
            type="primary"
            size="default"
            @click="dialogVisible = true"
            class="mrall"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 列表区域 -->
      <el-table :data="roleList" border stripe>
        <!-- 角色列表区域 -->
        <el-table-column type="expand">
          <template v-slot="scop">
            <el-row
              class="bottom_bor vcenter"
              :gutter="20"
              v-for="item1 in scop.row.children"
              :key="item1.id"
            >
              <!-- 第一权限 -->
              <el-col :span="5" :offset="0">
                <el-tag
                  type=""
                  closable
                  @close="deleteRouteById(scop.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 第二权限 -->
              <el-col :span="19" :offset="0">
                <el-row
                  class="bottom_bor vcenter"
                  :gutter="20"
                  v-for="(item2, index) in item1.children"
                  :key="item2.id"
                  :data-index="index"
                >
                  <el-col :span="6" :offset="0">
                    <el-tag
                      type="success"
                      closable
                      @close="deleteRouteById(scop.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 第三权限 -->
                  <el-col :span="18" :offset="0">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="deleteRouteById(scop.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="slotProps">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRole(slotProps.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRole(slotProps.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetList(slotProps.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addClose"
    >
      <!-- 主体区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- footer底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
        <el-button @click="addFormRest">重置</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="editClose"
    >
      <!-- 主体区域 -->
      <el-form
        :model="editForm"
        :rules="editFormRef"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- footer底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑权限对话框 -->
    <el-dialog
      title="编辑权限"
      :visible.sync="setRoleVisible"
      width="50%"
      @close="closeEdit"
    >
      <!-- 主体区域 -->
      <el-tree
        ref="treeRef"
        :data="treeList"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="threeId"
      ></el-tree>
      <!-- footer底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="allRightId">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Route',
  data() {
    return {
      roleList: [],

      addForm: {
        roleName: '',
        roleDesc: '',
      },
      editForm: {
        id: '',
        roleName: '',
        roleDesc: '',
      },
      dialogVisible: false,
      editdialogVisible: false,
      setRoleVisible: false,

      addFormRules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
      },
      editFormRef: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
      },
      // 树形控件
      treeList: [],
      defaultProps: {
        label: 'authName',
        children: 'children',
      },
      threeId: [],
      rowId: '',
    }
  },
  created() {
    this.getRoleList()
  },

  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      // this.$message.success('获取列表成功')
      this.roleList = res.data
      // console.log(this.roleList)
    },

    addFormRest() {
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('请正确填写数据表')
        // console.log(this.addForm)
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('创建用户失败')
        this.$message.success('创建成功')
        this.dialogVisible = false
        this.getRoleList()
      })
    },
    addClose() {
      this.$refs.addFormRef.resetFields()
    },
    editClose() {
      this.$refs.editFormRef.resetFields()
    },
    async deleteRole(id) {
      const resFirm = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (resFirm !== 'confirm') {
        // console.log(resFirm)
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败！')
      this.$message.success('删除用户成功！')
      this.getRoleList()
    },
    editRole(data) {
      this.editdialogVisible = true
      this.editForm.id = data.id
      this.editForm.roleName = data.roleName
      this.editForm.roleDesc = data.roleDesc
    },
    async editUserForm() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('请正确填写用户信息')
        const arr = {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc,
        }
        console.log(arr)
        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.id,
          arr
        )
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('更新用户失败')
        this.$message.success('更新用户成功')
        this.editdialogVisible = false
        this.getRoleList()
      })
    },
    async deleteRouteById(srow, id) {
      const resFirm = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (resFirm !== 'confirm') {
        // console.log(resFirm)
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${srow.id}/rights/${id}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除权限失败！')
      this.$message.success('删除权限成功！')
      srow.children = res.data
    },
    // 获取权限tree
    async showSetList(row) {
      this.rowId = row.id
      const { data: res } = await this.$http.get('rights/tree ')
      if (res.meta.status !== 200) return this.$message.error('获取权限失败')
      this.treeList = res.data
      // console.log(this.treeList)
      this.getKeysId(row, this.threeId)
      this.setRoleVisible = true
    },
    // 递归
    getKeysId(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => this.getKeysId(item, arr))
    },
    closeEdit() {
      this.threeId = []
    },
    async allRightId() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      // console.log(keys)
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.rowId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
      this.setRoleVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
.el-tag,
.mrall {
  margin: 7px;
}
.bottom_bor {
  border-bottom: 1px solid #ccc;
}
div[data-index]:last-child {
  border-bottom: none;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>